<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 专项治理评分编辑 -->
    <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="editModel != 0 ? rules : {}" id="base-breadcrumb" style="position: relative">
      <a-spin :spinning="loading[0] || loading[1] || loading[2]">
        <!-- 基本信息 -->
        <a-card>
          <title-name title="基本信息"></title-name>
          <custom-form @getList="getEvalueList" :formList="formList" :form="form" :editModel="editModel == 0 || columns.length > 0 ? 'V' : ''" @selectOrg="selectOrg"></custom-form>
        </a-card>
        <!-- 打分表 -->
        <a-card v-if="editModel != 2 || nextStep" style="margin-bottom: 50px">
          <title-name :title="`${form.cateName || ''}打分表`"></title-name>
          <s-table ref="table" size="default" rowKey="id" :columns="columns" bordered :data="loadData" :showPagination="false">
            <!-- 检查情况 -->
            <div v-if="columns.length > 0" :slot="columns.length > 0 ? columns.find((item) => item.code === '-1').dataIndex : ''" slot-scope="text, record">
              <BaseInput
                v-if="(record.defaultScore || record.evalue) && editModel != 0"
                style="width: 100%"
                :maxLength="300"
                placeholder="请输入检查情况"
                v-model="record[columns.find((item) => item.code === '-1').dataIndex]"
              ></BaseInput>
              <ellipsis v-if="editModel == 0" tooltip :length="45">{{ text }}</ellipsis>
            </div>
            <!-- 扣分 -->
            <div v-if="columns.length > 0" :slot="columns.length > 0 ? columns.find((item) => item.code === '-2').dataIndex : ''" slot-scope="text, record">
              <div v-if="editModel != 0">
                <a-row type="flex" :gutter="10" v-if="record.defaultScore || record.evalue" style="flex-wrap: nowrap">
                  <BaseInputNumber
                    style="width: 100%"
                    :max="Number(record[columns.find((item) => item.code === '4').dataIndex] || 0)"
                    :precision="2"
                    :min="0"
                    placeholder="请输入扣分"
                    v-model="record[columns.find((item) => item.code === '-2').dataIndex]"
                  ></BaseInputNumber>
                  <a class="ml12" @click="handleCancel(record)" style="flex-shrink: 0">取消扣分</a>
                </a-row>
              </div>
              <div v-if="editModel == 0">{{ record[columns.find((item) => item.code == '-2').dataIndex] }}</div>
              <template v-if="!record.defaultScore && !record.evalue">
                <a class="del_btn" v-if="editModel == 0">未扣分</a>
                <a v-else @click="record.evalue = true">扣分</a>
              </template>
            </div>
            <!-- 统计 -->
            <div align="right" slot="footer">
              <span class="mr20">总分：{{ total }}分</span>
              <span class="mr20">检查得分：{{ totalScore }}分</span>
              <span>换算百分制得分：{{ total ? ((totalScore * 100) / total).toFixed(2) : 0 }}分</span>
            </div>
          </s-table>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top">
        <a-button :loading="loading[2]" v-if="editModel == 2 && !nextStep" type="primary" class="button_right" @click="handleNext">下一步</a-button>
        <template v-else>
          <a-button :disabled="loading[0] || loading[1]" v-if="editModel == 1 && statusCode === '0' && form.version && form.version <= 1" type="danger" class="button_right" @click="handleRemove">删除草稿</a-button>
          <a-button :loading="loading[0]" :disabled="loading[1]" v-if="(editModel == 1 && (statusCode === '0' || statusCode === '3')) || editModel == 2" type="primary" class="button_right" @click="handleSubmit(0)">{{
            statusCode === '3' ? '保存' : '保存草稿'
          }}</a-button>

          <a-button :loading="loading[1]" :disabled="loading[0]" v-if="(editModel == 1 && (statusCode === '0' || statusCode === '3')) || editModel == 2" type="primary" class="button_right" @click="handleSubmit(1)"
            >提交</a-button
          >
        </template>
        <a-button type="primary" @click="$multiTab.close()">关闭</a-button>
      </div>
    </a-form-model>
  </base-breadcrumb>
</template>

<script>
import { STable, Ellipsis } from '@/components' // 表格
import { scoring } from '@/api/quality/quality' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
// import BaseInfo from '@/components/businessComponents/BaseInfo' // 基础信息
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目名称
import SelectGovScoreClass from '@/components/Select/SelectGovScoreClass' // 专项治理类型
import Selector from '@/components/Select/Selector' // 状态

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    // BaseInfo,
    STable,
    Ellipsis
  },
  data() {
    return {
      loading: { 0: false, 1: false, 2: false }, // 草稿和提交按钮loding:0 保存;1 提交;2 下一步
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      nextStep: false, // 是否为下一步
      id: '', // 业务id
      form: {
        evalMethodId: '',
        fillerDate: '',
        filler: '',
        viewName: ""
      }, // 表单
      statusCode: '', // 审批状态
      rules: {
        branchCompanyId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
        cateId: [{ required: true, message: '请选择专项治理类型', trigger: 'change' }],
        axisPart: [{ required: true, whitespace: true, message: '请输入轴线/部位', trigger: 'change' }],
        fileArrays: [{ type: 'array', required: true, message: '请上传文件', trigger: 'blur' }]
      },
      loadData: () => {
        if (this.editModel != 2 || this.nextStep) {
          let args = {}
          if (this.id) {
            args.id = this.id
          }
          this.loading[0] = true
          return scoring
            .getDetail(args)
            .then((res) => {
              if (res.data) {
                this.loading[0] = false
                let datas = this.$clone(res)
                // 映射项目信息
                this.form = datas.data || {}
                this.form.viewName = this.form.branchCompanyName + "/" + this.form.projectName
                this.id = res.data.id
                this.statusCode = res.data.statusCode
                const code1 = res.data.header.filter(item => item.code === '1')
                // 若表头是考核内容  将考核内容列一样的行合并
                if (code1.length > 0) {
                  const dataIndex = code1[0].dataIndex
                  const content = res.data.content
                  for (let i = 0;i< content.length; i++) {
                    let rowSpan = 1
                    let parentValue = content[i][dataIndex]
                    if (content[i].rowSpan === 0) {
                      continue;
                    }
                    for (let j = i + 1;j< content.length; j++) {
                      if (content[j][dataIndex] === parentValue) {
                        content[j].rowSpan = 0
                        rowSpan ++
                        content[i].rowSpan = rowSpan
                      } else {
                        break;
                      }
                    }
                  }
                  res.data.content = content
                }
                // 映射表头
                this.columns = res.data.header.map((item) => {
                  // 若表头是考核内容
                  if (item.code == '1') {
                    this.$nextTick(() => {
                      // 自定义单元格，将考核内容列一样的行合并
                      item.customRender = (value, row, index) => {
                        const obj = {
                          children: value,
                          attrs: {},
                        }
                        obj.attrs.rowSpan = res.data.content[index].rowSpan
                        return obj
                      }
                    })
                  }
                  // 若表头是考核情况、扣分时，自定义列
                  if (item.code === '-1' || item.code === '-2') {
                    item.scopedSlots = { customRender: item.dataIndex }
                    item.width = 260
                  }
                  item.ellipsis = true
                  return item
                })
                // 映射表格列表
                datas.data = res.data.content.map((item) => {
                  // 添加打分标志
                  item.defaultScore = item[this.$clone(res.data.header).find((item) => item.code == '-2').dataIndex]
                  item.evalue = item.defaultScore ? true : false
                  return item
                })
                // 列表对象
                this.content = datas.data
                return datas
              }
            })
            .catch((res) => {
              this.loading[0] = false
            })
        }
      },
      // 表头
      columns: [],
      content: []
    }
  },
  mounted() {
    this.$route.meta.title = ['专项治理评分查看', '专项治理评分编辑', '专项治理评分新增'][this.editModel]
    // 为添加操作时
    if (this.editModel == 2) {
      this.form.filler = JSON.parse(sessionStorage.getItem('ycloud-user_info'))?.name // 默认填报人
      this.form.fillerDate = this.$dateFormat(new Date(), 'D') // 默认填报时间
    }
  },
  computed: {
    // 总分
    total() {
      let total = 0
      let dataIndex = this.columns.find((item) => item.code === '4')?.dataIndex //得分字段
      let content = this.content.filter((item) => item.evalue) // 评分列表
      if (content.length === 1) {
        total = content[0][dataIndex] || 0
      } else if (content.length > 1) {
        total = content.reduce((t, i) => {
          return Number(t[dataIndex] || t || 0) + Number(i[dataIndex] || 0)
        })
      }
      return total
    },
    // 得分
    totalScore() {
      let total = 0
      let dataIndex = this.columns.find((item) => item.code === '-2')?.dataIndex //扣分字段
      let dataIndex2 = this.columns.find((item) => item.code === '4')?.dataIndex //得分字段
      let content = this.content.filter((item) => item.evalue) // 评分列表
      if (content.length === 1) {
        // 扣分超过限制则为0
        total = Number(content[0][dataIndex] >= 0) && Number(content[0][dataIndex]) <= Number(content[0][dataIndex2]) ? content[0][dataIndex] : 0
      } else if (content.length > 1) {
        total = content.reduce((t, i) => {
          return (
            Number(t[dataIndex] || t || 0) + Number(Number(i[dataIndex]) >= 0 && Number(i[dataIndex]) <= Number(i[dataIndex2]) ? i[dataIndex] : 0) // 扣分超过限制则为0
          )
        })
      }
      return this.total - total < 0 ? 0 : (this.total - total).toFixed(2)
    },
    // 登陆人组织类型
    orglevel() {
      return sessionStorage.getItem('currentLevel') ?? ''
    },
    // 表单列表
    formList() {
      return [
        // {
        //   type: SelectSubCompany,
        //   keyName: 'branchCompanyId',
        //   label: '所属分公司',
        //   viewName: 'branchCompanyName',
        //   attrs: {
        //     autoSelected: this.editModel == 2
        //   }
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   label: '所属项目',
        //   viewName: 'projectName',
        //   attrs: {
        //     autoSelected: this.editModel == 2,
        //     keyValue: 'branchCompanyId',
        //     isClear: this.editModel == 2,
        //     form: this.form
        //   }
        // },
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst: this.editModel == 2,
          isNeedAuth:true ,
          checkStrictly: true,
          disabled: this.editModel == 0,
          isNoBorder: !!this.id,
          viewName: "viewName",
        },
        {
          keyName: 'evalMethodId',
          viewName: 'evalMethodName',
          disabled: true,
          type: Selector,
          label: '评价方式',
          attrs: {
            selectType: '21'
          }
        },
        {
          type: SelectGovScoreClass,
          keyName: 'cateId',
          viewName: 'cateName',
          label: '专项治理类型'
        },
        {
          keyName: 'axisPart',
          type: 'a-input',
          label: '轴线/部位',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'filler',
          type: 'a-input',
          disabled: true,
          label: '填报人'
        },
        {
          keyName: 'fillerDate',
          type: 'a-date-picker',
          disabled: true,
          label: '填报时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        }
      ]
    }
  },
  methods: {
    selectOrg(val) {
      if(val&&val.length) {
        this.form.branchCompanyId = val[val.length - 2].orgId
        this.form.viewName = val[val.length - 2].orgName + "/" + val[val.length - 1].projectName
      }
    },
    /**
     * 取消评分
     */
    handleCancel(e) {
      let memo = e[this.columns.find((item) => item.code === '-1').dataIndex] // 检查情况
      let value = e[this.columns.find((item) => item.code === '-2').dataIndex] // 扣分
      // 取消打分
      e.evalue = false
      // 重置检查情况
      memo && (e[this.columns.find((item) => item.code === '-1').dataIndex] = '')
      // 重置初始扣分值和真实扣分值
      e.defaultScore = ''
      e[this.columns.find((item) => item.code === '-2').dataIndex] = ''
    },
    /**
     * 获取评分方式列表
     */
    getEvalueList(name, e) {
      if (name === 'evalMethodId') {
        // 默认映射当前登录人评分方式
        e?.length > 0 && (this.form.evalMethodId = e.find((item) => item.code == this.orglevel)?.id)
      }
    },
    /**
     * 项目改变时
     */
    handleChange(name) {
      if (name === 'projectId') {
        let form = this.form
        if (form.editorEmployeeId) {
          form.editorEmployeeId = ''
        } else {
          this.$set(this.form, 'editorEmployeeId', '')
        }
      }
    },
    /**
     * 下一步
     */
    handleNext() {
      let that = this
      that.$refs.ruleForm.validate((e) => {
        if (e) {
          that.$confirm({
            title: '温馨提示',
            content: '生成评分表后基本信息不能再修改，确认进行下一步？',
            onOk: () => {
              // 校验表单
              return new Promise((resolve, reject) => {
                that.$refs.ruleForm.validate((e) => {
                  if (e) {
                    // 提交表单
                    let form = that.$clone(that.form)
                    form.statusCode = 0
                    scoring
                      .create(form)
                      .then((res) => {
                        resolve()
                        that.$message.success('生成评分表成功！')
                        that.id = res.data.id
                        that.nextStep = true // 进行下一步
                      })
                      .catch((res) => {
                        // that.$message.warning(res?.data?.message || '生成评分表失败！')
                        reject()
                      })
                  }
                })
              })
            }
          })
        }
      })
    },
    /**
     * 删除草稿
     */
    handleRemove() {
      this.$confirm({
        title: '温馨提示',
        content: '确定删除草稿？',
        onOk: () => {
          return scoring.remove({ id: this.id }).then((res) => {
            this.$message.success('删除成功！')
            // 关闭当前页
            this.$multiTab.close()
          })
          // .catch((res) => {
          //   this.$message.warning('删除失败！')
          // })
        }
      })
    },
    /**
     * 提交表单
     */
    handleSubmit(statusCode) {
      let that = this
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e) {
          let content = that.$clone(that.content)
          let dataIndex = that.columns.find((item) => item.code == '-2').dataIndex // 扣分的key
          // 判断是否有激活评分项
          if (that.$clone(content).filter((item) => item.evalue)?.length > 0 || statusCode == 0) {
            // 提交表单
            that.loading[statusCode] = true
            let form = that.$clone(that.form)
            content.forEach((item) => {
              item.evalue && (item[dataIndex] = item[dataIndex] || '0')
            })
            form.content = content
            form.statusCode = that.statusCode == '3' && statusCode == 0 ? that.statusCode : statusCode
            scoring
              .update(form)
              .then((res) => {
                that.loading[statusCode] = false
                that.$message.success(['保存', '提交'][statusCode] + '成功！')
                that.$multiTab.close()
              })
              .catch((res) => {
                // that.$message.warning(['保存', '提交'][statusCode] + '失败！')
                that.loading[statusCode] = false
              })
          } else {
            this.$message.warning('请评分后操作！')
          }
        }
      })
    }
  }
}
</script>
